from helpers.director.shortcut import page_dc
from .models import QualityEvent
from django.utils import timezone
from helpers.func.collection.mylist import complement
from django.db.models.functions import Trunc
from django.db.models import DateField,Count,F
from helpers.func.monthDelta import relativedelta
from helpers.director.access.permit import has_permit
from django.core.exceptions import PermissionDenied

class StatisHomePage(object):
    def __init__(self, request,engin):
        self.request = request
        self.crt_user = request.user
    
    def get_label(self):
        return '整体分析'
    
    def get_template(self):
        return 'jb_admin/live.html'
    
    def check_permit(self):
        if not has_permit(self.crt_user,'ansys_data'):
            raise PermissionDenied('不能查看图表分析')

    def get_context(self):
        now = timezone.now()
        day_7_ago = timezone.now()-timezone.timedelta(days=7)
        flow_count =  QualityEvent.objects.exclude(status=5).count()
        month_start = timezone.now().strftime('%Y-%m-01')
        ago_7_count =  QualityEvent.objects.filter(create_time__date__gte=day_7_ago.date()).count()
        current_month = QualityEvent.objects.filter(create_time__date__gte =month_start ).count()
        # 30 天统计
        day_30_x =[]
        for ii in range(30):
            this_day = now - timezone.timedelta(days=ii)
            day_30_x.append(this_day.strftime('%Y-%m-%d'))
        day_30_x = list( reversed(day_30_x) )
        day_30_y_orgin=[]
        for inst in QualityEvent.objects.filter(create_time__date__gte=this_day).annotate(day = Trunc('create_time','day',output_field=DateField())).values('day')\
            .annotate(cnt=Count('id')):
            day_30_y_orgin.append({'date':inst['day'].strftime('%Y-%m-%d'),'cnt':inst['cnt']})
            
        day_30_y=  complement(day_30_x,day_30_y_orgin,lambda row,target: row['cnt'] if row['date'] == target else 0  )
        
        # 12个月统计
        month_12_x =[]
        for ii in range(30):
            this_month = now - relativedelta(months=ii)
            month_12_x.append(this_month.strftime('%Y-%m'))
        month_12_x = list( reversed(month_12_x)  )
        month_12_ago = this_month.strftime('%Y-%m-%d')
        month_12_orgin = []
        for inst in QualityEvent.objects.filter(create_time__date__gte= month_12_ago).annotate(month = Trunc('create_time','month')).values('month')\
            .annotate(cnt=Count('id')):
            month_12_orgin.append({'month':inst['month'].strftime('%Y-%m'),'cnt':inst['cnt']})
        month_12_y=complement(month_12_x, month_12_orgin, lambda row,target: row['cnt'] if row['month'] == target else 0 )
        
        # 不合格来源
        fail_source=[]
        for inst in QualityEvent.objects.filter(create_time__date__gte= now-timezone.timedelta(days=360) ).annotate(source=F('fail_source__name')).values('source')\
            .annotate(cnt=Count('id')):
            fail_source.append({
                'value':inst['cnt'],
                'name':inst['source']
            })
        # 不合格类别
        fail_kind = []
        for inst in QualityEvent.objects.filter(create_time__date__gte= now-timezone.timedelta(days=360) ).annotate(fail_kind_name=F('fail_kind__name')).values('fail_kind_name')\
            .annotate(cnt=Count('id')):
            fail_kind.append({
                'value':inst['cnt'],
                'name':inst['fail_kind_name']
            })        
        return {
            'editor':'statisHome',
            'editor_ctx':{  
                'eventdata':[
                    {'fa':'cogs','title':'流转事件','info':flow_count,'type':'success'},
                    {'fa':'bell','title':'7日事件','info':ago_7_count,'type':'info'},
                    {'fa':'bell-o','title':'本月事件','info':current_month,'type':'primary'},
                    
                ],
                'event_30day_trend':{
                   'x':day_30_x,
                   'y':day_30_y
                  },
                'month_12_trend':{
                    'x':month_12_x,
                    'y':month_12_y
                },
                'fail_source':fail_source,
                'fail_kind':fail_kind,
               
                
            }
        }
    
page_dc.update({
    'statis_home':StatisHomePage
})